//
//  TLNotificationCenterViewController.swift
//  TLiOS26LiquidGlassDemo
//
//  Created by jiayin on 2025/7/14.
//

import UIKit

/**
 新技术功能介绍：
 1.UIKit 带来了强类型通知，为通知系统带来了期待已久的类型与并发安全性。
 2.不再使用基于字符串的标识符以及通过userInfo字典传递数据，该种方式存在线程安全、拼写错误、类型转换等问题。
 3.通过全新的并发安全通知协议NotificationCenter.MainActorMessage（主线程消息）与NotificationCenter.AsyncMessage（异步消息）可以做到编译时检测，从而提前发现潜在的问题。
 4.与老版本的通知系统完全兼容。
 */
public class TLNotificationSubject {
    static let shared = TLNotificationSubject()
}

// MARK: - 消息类型
public struct TLNotificationCustomMainActorMessage: NotificationCenter.MainActorMessage {
    // 发送者
    public typealias Subject = TLNotificationSubject
    public static var name: Notification.Name {
        .init("CustomMainActorMessage")
    }

    // 数据
    let info: String
}

class TLNotificationCenterViewController: UIViewController {
    lazy var label: UILabel = {
        let label = UILabel()
        label.frame = CGRect(x: 0, y: 0, width: 300, height: 60)
        label.textAlignment = .center
        label.text = "暂无通知消息"
        label.center = view.center
        return label
    }()

    var mainActorMessageToken: NotificationCenter.ObservationToken!

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        view.addSubview(label)
        // 监听通知
        mainActorMessageToken = NotificationCenter.default.addObserver(of: TLNotificationSubject.shared, for: TLNotificationCustomMainActorMessage.self) { message in
            self.label.text = "\(message.info)"
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        // 发送通知
        NotificationCenter.default.post(TLNotificationCustomMainActorMessage(info: "you have a new message"), subject: TLNotificationSubject.shared)
    }

    deinit {
        NotificationCenter.default.removeObserver(mainActorMessageToken ?? "")
    }
}

